<?php
namespace app\common\service;

use app\common\helper\BaseHelper;
use app\common\helper\WeixinHelper;
use app\common\util\Upload;
use app\common\util\Util;
use think\Model;
use app\common\model\SystemNews;
use think\Request;
use app\common\model\TopicView;

/**
 * 权限相关的服务
 * 调用第三发类库里面的功能的
 * Class AuthService
 * @package app\common\service
 */
class AuthService extends BaseService
{

    /**
     * 添加管理员
     * @param $sid 店铺ID
     * @param $mobile 手机号码
     * @param $password 密码
     */
    public function addStoreAdmin($sid, $mobile, $password, $role_id, $uid)
    {
//        $admin_num = db('store_admin')->where(array('sid' => $sid, 'is_admin' => 0))->count();
//        if ($admin_num >= 5) {
//            return ['status' =>0,'msg' =>'只能创建五个店铺子管理员！'];
//        }

        $s = db('store_admin')->where(['username' => Util::tel_encode($mobile), 'status' => 1])->find();
        if ($s) {
            return ['status' =>0,'msg' =>'电话号已存在'];
        }

        $data = [
            'sid' => $sid,
            'username' => Util::tel_encode($mobile),
            'password' => md5($password),
            'add_time' => time(),
            'status' => 1,
            'is_admin' => 0,
            'role_id' => $role_id,
            'uid' => $uid ?? 0,
            'qrcode_bind_status' => 0
        ];

        $r = db('store_admin')->insert($data);

        if ($r === false) {
            return ['status' =>0,'msg' =>'添加失败,写入数据库失败'];
        } else {
            $service = new WxTplMsgService();
            $service->send($sid, $uid, 'bind_manager');
            return ['status' =>1];
        }
    }

    /**
     * 编辑管理员
     * @param $sid
     * @param $id
     * @param $role_id
     * @param $uid
     * @return array|int|string
     * @throws \think\Exception
     */
    public function editStoreAdmin($sid, $id, $role_id, $uid)
    {

     /*   $username = db('store_admin')->where(['aid' => $id])->value('username');
        if (!empty($password)) {
            db('store_admin')->where(['aid' => $id])->setField('password', md5($password));
        }
        if ($postname != Util::tel_encode($username)) {
            $admin = db('store_admin')->where(['username' => Util::tel_encode($postname)])->find();
            if ($admin) {
                return ['status' =>0,'msg' =>'电话号已存在'];

            } else {
                db('store_admin')->where(['aid' => $id])->setField('username', Util::tel_encode($postname));
            }
        }
        return ['status' =>1];*/

        $where = ['sid' => $sid, 'aid' => $id, 'status' => ['<>', -1]];
        $info = db('store_admin')->where($where)->find();
        if(!$info){
            return ['status' => 0, 'msg' => '管理员不存在'];
        }

        $data = [
            'role_id' => $role_id,
            'uid' => $uid ?? 0
        ];

        // 更换了绑定的微信用户
        if($info['uid'] != $uid){
            $data['qrcode_bind_status'] = 0;
        }

        $r = db('store_admin')->where($where)->update($data);
        if($r !== false){
            if($r != 0){
                $service = new WxTplMsgService();
                $service->send($sid, $uid, 'bind_manager');
            }

            return ['status' => 1, 'msg' => '编辑成功'];
        } else {
            return ['status' => 0, 'msg' => '编辑失败'];
        }
    }


    /**
     * 重置管理员密码
     * @param $sid
     * @param $admin_id
     * @param $password
     * @return array
     */
    public function resetPassword($sid, $admin_id, $password)
    {
        $where = [
            'sid' => $sid,
            'aid' => $admin_id,
            'status' => ['<>', -1]
        ];
        $info = db('store_admin')->where($where)->find();
        if(!$info){
            return ['status' => 0, 'msg' => '管理员不存在'];
        }

        $password = trim(md5($password));
        if($info['password'] == $password){
            return ['status' => 0, 'msg' => '新密码和旧密码一致'];
        }

        $r = db('store_admin')->where($where)->setField('password', $password);
        return $r ? ['status' => 1, 'msg' => '修改成功'] : ['status' => 0, 'msg' => '修改失败'];
    }

    /**
     * 删除管理员
     * @param $admin_id 数组就是批量删除
     * @return array
     */
    public function deleteStoreAdmin($sid,$admin_id)
    {

        //$d['id'] = I('post.id');

        if (is_array($admin_id)) {
            foreach ($admin_id as $value) {
                $r = db('store_admin')->where(array('aid' => $value, 'is_admin' => 0))->delete();
                $access = M('store_access')->where(array('uid' => $value))->find();
                if ($access) {
                    db('system_access')->where(array('uid' => $value))->delete();
                }
                if ($r === false) {
                    return ['status' =>0,'msg' =>'操作失败'];

                }
            }
        } else {
            $r = db('store_admin')->where(array('aid' => $admin_id, 'is_admin' => 0))->delete();
            $access = db('store_access')->where(array('uid' => $admin_id))->find();
            if ($access) {
                db('system_access')->where(array('uid' => $admin_id))->delete();
            }
            if ($r === false) {
                return ['status' =>0,'msg' =>'操作失败'];

            }
        }
        return ['status' =>1];

    }
    public function setStoreAdminGroup($sid,$admin_id,$group_id) {

        $access = db('store_access')->where(array('uid' => $admin_id))->find();
        if ($access) {
            $r = db('store_access')->where(array('uid' => $admin_id))->update(['group_id'=> $group_id]);
        } else {
            $r = db('store_access')->insert(array('uid' => $admin_id, 'group_id' => $group_id));
        }

        if ($r === false) {
            return ['status' =>0,'msg' =>'操作失败'];

        }
        else
        {
            return ['status' =>1];
        }
    }
    public function listStoreAdmin($sid)
    {
        /*$map = array('d.sid' => $sid, 'd.is_admin' => 0, 'd.status' => array('neq', -1));

        $admin_list = db()->name('store_admin')
            ->alias('d')
            ->join('store_access s','d.aid = s.uid','LEFT')
            ->join('system_group g','g.id = s.group_id and g.sid = d.sid','LEFT')
            ->where($map)
            ->field('d.username,d.status,d.lastlogintime,d.lastloginip,d.aid,g.title,g.id as group_id,d.password')
            ->select();

        foreach($admin_list as $k=>&$v)
        {
            $v['username'] = Util::tel_decode($v['username']);
        }
        return ['status' =>1,'data'=>$admin_list];*/
        $where = [
            'sa.sid' => $sid,
            'sa.is_admin' => 0,
            'sa.status' => ['<>', -1]
        ];
        $field = 'sa.aid,sa.status,sa.username,sa.qrcode_bind_status,sr.role_id,sr.role_name,u.user_id,u.user_nickname,u.user_headimgurl';
        $list = db('store_admin sa')
                ->join('store_role sr', 'sa.role_id=sr.role_id')
                ->join('user u', 'u.user_id=sa.uid', 'LEFT')
                ->where($where)
                ->field($field)
                ->select();
        if($list){
            foreach($list as $k => &$v){
                $v['username'] = Util::tel_decode($v['username']);
            }
        }
        return $list;
    }


    public function setStoreAdminHide($admin_id,$hide) {

        $r = db('store_admin')->where(array('aid' => $admin_id))->update(['status'=>$hide,'update_time'=>time()]);
        if ($r) {
            return ['status' =>1]; //$this->apiResult('',200,'设置成功');
        }
        else{
            return ['status' =>0,'msg' =>'操作失败'];
        }

    }

    public function listStoreGroup($sid) {
        $map = array('module' => 'store', 'type' => 1, 'sid' => $sid, 'status' => array('neq', -1));
        $group = db('system_group')->where($map)->field(true)->select();

        return ['status' =>1,'data'=>$group];
    }

    public function addStoreGroup($sid,$title,$description) {

        $data = array(
            'title' => $title,
            'description' => $description,
            'sid' => $sid,
            'module' => 'store',
            'type' => 1,
            'status' => 1,
            'rules'=>''
        );
        $r = db('system_group')->insert($data);
        if ($r) {
            return ['status' =>1]; //$this->apiResult('',200,'设置成功');
        }
        else{
            return ['status' =>0,'msg' =>'操作失败'];
        }

    }

    public function editStoreGroup($sid,$group_id,$title,$description) {

        //$title = $this->request->post('title');
        //$description = $this->request->post('description');

        $data = array(
            'title' => $title,
            'description' => $description
        );
        $r = M('system_group')->where(array('id' => $group_id))->update($data);
        if ($r === false) {
            return ['status' =>1];
        }
        else{
            return ['status' =>0,'msg' =>'操作失败'];
        }

    }

    public function deleteStoreGroup($sid,$group_id) {
        $r = db('system_group')->where(array('id' => $group_id))->update(['status'=>-1]);
        db('store_access')->where(array('group_id' => $group_id))->update(['group_id'=>null]);
        if ($r) {
            return ['status' =>1];
        }
        else{
            return ['status' =>0,'msg' =>'操作失败'];
        }
    }

    public function setStoreGroupHide($sid,$group_id,$hide) {

        $r = db('system_group')->where(array('id' => $group_id))->update(['status'=>$hide]);
        if ($r) {
            return ['status' =>1];
        }
        else{
            return ['status' =>0,'msg' =>'操作失败'];
        }
    }

    public function childStoreAccess($sid,$group_id) {

        $data = array();

        $auth_group = db('system_group')->where(array('module' => 'store', 'type' => 1))->field(true)
            ->find($group_id);
        if ($auth_group && -1 != $auth_group['status']) {
            if (!empty($auth_group['rules'])) {
                $rules = explode(',', $auth_group['rules']);
                $auth_group['rules'] = $rules;
            }
            $data['auth_group'] = $auth_group;
            //print_r($auth_group);
            //$this->assign('auth_group', $auth_group);
        } else {
            return ['status' =>0,'msg' =>'用户组不存在或已被删除'];
            //$this->error('用户组不存在或已被删除');
        }

        $store_type = db('store')->where(array('store_id' => $sid))->value('store_type');



        $rules = db('system_group')->where(array('id' => $store_type))->value('rules');
        if (is_string($rules)) {
            if (strpos($rules, ',') !== false) {
                $rules = explode(',', $rules);
            }
        }
        $channel = db('system_channel')->where(array('id' => array('in', $rules)))->order('sort asc')->field('title,id,pid,sort,group,hide')->select();
        /* 		$groups  = M('system_channel')->where(array('id'=>array('in',$rules)))->distinct(true)->field('group')->select();
          if ($groups) {
          $groups = array_column($groups, 'group');
          } else {
          $groups = array();
          } */



        $tree = \app\common\util\Util::list_to_tree($channel);
        foreach ($tree as $k => $v) {
            foreach ($v['_child'] as $x => $y) {
                $g = db('system_channel')->where(array('group' => $y['group']))->field('id,pid,title,url,tip,group')->order('sort asc')->select();
                $tree[$k]['_child'][$y['group']] = $g;
                unset($tree[$k]['_child'][$x]);
            }
        }

        $data['channe_list'] = $tree;
        return ['status' =>1,'data' =>$data];
    }

    /**
     * 保存组权限
     */
    public function saveStoreAccess($sid,$group_id,$rules)
    {
        sort($rules);
        $rules = implode(',', array_unique($rules));

        $r = db('system_group')->where(array('id' => $group_id))->update(['rules' => $rules]);
        if ($r === false) {
            return ['status' => 0, 'msg' => '用户组不存在或已被删除'];
        } else {
            return ['status' => 1];
        }
    }


    /**
     * 后台: 通过帐号获取管理员权限
     * @param $sid
     * @param $username
     * @return array
     */
    public function getPermissionsByUsername($sid, $username)
    {
        $where = [
            'sid' => $sid,
            'username' => Util::tel_encode($username),
            'status' => 1
        ];
        $admin = db('store_admin')->where($where)->find();
        if(!$admin){
            return ['status' => 0, 'msg' => '管理员信息不存在'];
        }

        // 判断是否为超级管理员
        if($admin['is_admin']){
            return ['data' => ['is_admin' => $admin['is_admin']], 'status' => 1, 'msg' => '获取成功'];
        }

        $role = db('store_role')->where(['sid' => $sid, 'role_id' => $admin['role_id'], 'status' => 1])->find();
        if(!$role){
            return ['status' => 0, 'msg' => '角色信息不存在'];
        }

        $permissions = $role['permissions'] ? explode(',', $role['permissions']) : [];
        $data = [
            'is_admin' => 0,
            'permissions' => $permissions
        ];
        return ['data' => $data, 'status' => 1, 'msg' => '获取成功'];
    }
}